package com.lucas.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lucas.exception.MyException;
import com.lucas.mapper.UserMapper;
import com.lucas.pojo.Lagou_user;
import com.lucas.service.CodeService;
import com.lucas.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Map;

/**
 * @program: spring_cloud_lagou_homework
 * @author: lucasLu
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, Lagou_user> implements UserService {

    @Autowired
    private CodeService codeService;

    @Override
    public boolean register(String email, String password, String code) {
        boolean registered = isRegistered(email);
        if(registered){
            throw new MyException("该邮箱已经注册");
        }
        Integer codeValid = codeService.validateCode(email, code);
        //0正确 1错误 2超时
        if(codeValid != 0){
            if (codeValid == 1) {
                throw new MyException("验证码错误");
            } else if (codeValid == 2) {
                throw new MyException("验证码已经失效");
            } else {
                throw new MyException("验证码异常");
            }
        }
        Lagou_user lagou_user = new Lagou_user();
        lagou_user.setCreatetime(Calendar.getInstance().getTime());
        lagou_user.setEmail(email);
        lagou_user.setPassword(password);
        return  baseMapper.insert(lagou_user)>0;
    }

    @Override
    public boolean isRegistered(String email) {
        Lagou_user  lagou_user = new Lagou_user();
        lagou_user.setEmail(email);
        QueryWrapper<Lagou_user> queryWrapper = new QueryWrapper(lagou_user);
        return baseMapper.selectOne(queryWrapper)!=null;
    }

    @Override
    public boolean login(String email, String password) {
        Lagou_user lagou_user = new Lagou_user();
        lagou_user.setEmail(email);
        lagou_user.setPassword(password);
        QueryWrapper<Lagou_user> queryWrapper = new QueryWrapper<>(lagou_user);
        return baseMapper.selectOne(queryWrapper)!=null;
    }
}
